<?php

namespace app\admin\controller;

use addons\epay\library\Service;
use addons\recharge\model\MoneyLog;
use app\common\controller\Backend;
use app\common\model\DeviceRefind;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use Yansongda\Pay\Pay;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class DeviceOrder extends Backend
{

    /**
     * DeviceOrder模型对象
     * @var \app\common\model\DeviceOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\DeviceOrder;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("deviceStatusList", $this->model->getDeviceStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['ground','device','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('ground')->visible(['name']);
				$row->getRelation('device')->visible(['name']);
				$row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function refund($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $order_id = $id;
        $price = $params['money'];
        if ($order_id) {
            //查询是否已存在
            $refind = DeviceRefind::where('order_id', $order_id)->find();
            if ($refind) {
//                $this->error('已存在退款申请');
            }
            $order = \app\common\model\DeviceOrder::find($order_id);

            //查询退款金额是否大于订单金额
            if ($price > $order->amount) {
                $this->error('退款金额不能大于订单金额');
            }
            //查询此订单所有收益
            $money_log = MoneyLog::where('order_id', $order_id)->where('memo','设备佣金结算')->select();
            $is_true = true;
            foreach ($money_log as $k => $v){
                $user = User::find($v['user_id']);
                if($user->money < $v['money']){
                    $is_true = false;
                }
            }
            if (!$is_true){
                $this->error('退款失败，请联系管理员');
            }

            if ($order) {
                Db::startTrans();
                try {
                    $refind = new DeviceRefind();
                    $refind->order_id = $order_id;
                    $refind->ground_id = $order->ground_id;
                    $refind->device_id = $order->device_id;
                    $refind->user_id = $order->user_id;
                    $refind->price = $price;
                    $refind->save();
                    if($order->paytype = 'wechat'){
                        $payData = [
                            'out_trade_no' => $order->orderid,
                            'out_refund_no' => time(),
                            'total_fee' => $order->payamount * 100,
                            'refund_fee' => $price * 100,
                            'refund_desc' => '订单退款',
                        ];
                        $config = Service::getConfig();
                        $result = Pay::wechat($config)->refund($payData);

                    }else{
//                        User::money($price,$order->user_id, '订单退款', $order->ground_id, $order->device_id, $order->id);
                        $price = $price - $order->gifts_money;
                        if($price > 0){
                            User::money($price,$order->user_id, '订单退款', $order->ground_id, $order->device_id, $order->id);
                        }
                        if($order->gifts_money > 0){
                            User::gifts_money($order->gifts_money,$order->user_id, '订单退款', $order->ground_id, $order->device_id, $order->id);
                        }
                    }
                    foreach ($money_log as $k => $v){
                        User::money($v['money'],$v['user_id'], '订单退款回收佣金', $order->ground_id, $order->device_id, $order->id);
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error('退款失败');
                }

                $this->success('退款成功');
            } else {
                $this->error('订单不存在');
            }
        } else {
            $this->error('参数错误');
        }
        $this->success();
    }

}
